package com.jiwei.community.handler.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jiwei.community.utils.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author 季伟
 * 功能：mybatis自动填充处理
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler{

    @Override
    public void insertFill(MetaObject metaObject) {

        Long userId;
        try {
            userId = SecurityUtils.getUserId();
            //可能因为注册的时候插入一个用户但是没登录找不到userId而报指针异常
        } catch (Exception e) {
            userId = -1L;
        }
        if (ObjectUtils.isEmpty(this.getFieldValByName("createBy",metaObject))){
            this.setFieldValByName("createBy",userId,metaObject);
        }
        if (ObjectUtils.isEmpty(this.getFieldValByName("createTime",metaObject))){
            this.setFieldValByName("createAt",new Date(),metaObject);
        }
        this.setFieldValByName("updateBy",userId,metaObject);
        this.setFieldValByName("updateAt",new Date(),metaObject);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId;
        try {
            userId = SecurityUtils.getUserId();
            //可能因为没登录找不到userId而报指针异常
        } catch (Exception e) {
            userId = -1L;
        }
        if (userId != -1L){
            this.setFieldValByName("updateBy",userId,metaObject);
        }
        this.setFieldValByName("updateAt",new Date(),metaObject);

    }
}
